/*************************************************************************************
 * ADD CLASS
 * ***********************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;

/************************************************************************************
 * NAMESPACE
 * **********************************************************************************/

namespace UART_GUI_C_sharp
{
    public partial class FrmUart : Form
    {
         /************************ Public definition *********************************/

        [STAThread]
        [DllImport("USER32.DLL", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("USER32.DLL", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
        [DllImport("user32.dll")]
        static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

        public const int VK_UP = 0x26, BK_UP = 0xC8;
        public const int VK_LEFT = 0x25, BK_LEFT = 0xCB;
        public const int VK_DOWN = 0x28, BK_DOWN = 0xD0;
        public const int VK_RIGHT = 0x27, BK_RIGHT = 0xCD;
        public const int VK_ENTER = 0x0D, BK_ENTER = 0x9C;
        public const int VK_SPACE = 0x20, BK_SPACE = 0xB9;
        public const int KEYUP = 0x02;
        public const int KEYDOWN = 0;

        int intlen = 0; //tong so port COM
        int on = 0; //tinh trang dang chay hay dung cua chuong trinh

        /*****************************************************************************/

        public FrmUart()
        {
            InitializeComponent();
            cbbChooseGame.Items.Add("Gold Miner");
            cbbChooseGame.Items.Add("Snake");
            cbbChooseGame.Items.Add("Bomberman");
            cbbChooseGame.Items.Add("Tetris 2000");
        }
        
        /****************************************************************************
         * OBJECTs
         * **************************************************************************/
        private void timer1_Tick(object sender, EventArgs e)
        {
            //code dung timer de tu dong cap nhat COM ket noi
            
            string[] ports = SerialPort.GetPortNames(); //lay tat ca port dg ket noi
            if (intlen != ports.Length)
            {
                intlen = ports.Length;
                List.Items.Clear();
                for (int j = 0; j < intlen; j++)
                {
                    List.Items.Add(ports[j]);
                }
            }
        }

        /****************************************************************************/
        private void List_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        /****************************************************************************/
        private void OnCOM(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //doc 1 byte se ngat COM
            string s;
            s = COM.ReadExisting(); //doc tat ca du lieu trong buffer cua COM
            //txt.Receive.Text = s (lenh nay bi loi thay bang lenh duoi dung delegate)
            Display(s);
        }
        
        /****************************************************************************/
        private delegate void DlDisplay(string s);

        private void Display(string s)
        {
            if (txtReceive.InvokeRequired)
            {
                DlDisplay sd = new DlDisplay(Display);
                txtReceive.Invoke(sd, new Object[] { s });
            }
            else
            {
                txtReceive.Text = s;
            }
        }

        /****************************************************************************/
        private void PbConnect_Click(object sender, EventArgs e)
        {
            if (LbStatus.Text == "Disconnect")
            {
                COM.PortName = List.Text;
                COM.Open();
                LbStatus.Text = "Connect";
                PbConnect.Text = "Disconnect";
            }
            else
            {
                COM.Close();
                LbStatus.Text = "Disconnect";
                PbConnect.Text = "Connect";
            }
        }

        /****************************************************************************/
        private void PbSend_Click(object sender, EventArgs e)
        {
            string s;
            if (LbStatus.Text == "Connect")
            {
                s = txtSend.Text;
                COM.WriteLine(s);
            }
        }
        
        /****************************************************************************/
        private void PbStart_Click(object sender, EventArgs e)
        {
            string s;
            const string s1 = "1", s2 = "2", s3 = "3", s4 = "4", s5 = "5";
            int stt = 0, count = 0;
            bool hold;

            //On off switch
            if (on == 1)
            {
                PbStart.Text = "Start Game";    //program switches to off
                on = 0;
                return;
            }
            PbStart.Text = "Stop";              //program switches to on
            on = 1;

            switch (cbbChooseGame.Text)
            {
                case "Gold Miner":
                    Process game1 = Process.Start("C:\\Users\\My Computer\\Desktop\\flash\\Dao_vang.exe");
                    break;
                case "Snake":
                    Process game2 = Process.Start("C:\\Users\\My Computer\\Desktop\\flash\\SNAKE.exe");
                    break;
                case "Bomberman":
                    Process game3a = Process.Start("C:\\Users\\My Computer\\Desktop\\Play Bomberman II.lnk");
                    break;
                case "Tetris 2000":
                    Process game4 = Process.Start("C:\\Program Files\\Tetris2000\\Tetris2000.exe");
                    break;
            }

            while (on==1)
            {
                    
                    Application.DoEvents();         //do things in app queque and keep form actice
                    hold = !chbSingleClick.Checked; //single click or not
                           
                    //Read s until valid    
                    do
                    {
                        s = COM.ReadExisting();
                        Application.DoEvents();
                    }
                    while (s == "");
                    
                    //processing signal s
                    switch (s[0])
                    {
                            case '1':       //down
                                keybd_event(VK_DOWN, BK_DOWN, KEYDOWN, 0);
                                if (stt != 1)
                                {
                                    Thread.Sleep(200);
                                    stt = 1;
                                }
                                break;
                            case '2':       //right
                                keybd_event(VK_RIGHT, BK_RIGHT, KEYDOWN, 0);
                                if (stt != 2)
                                {
                                    Thread.Sleep(200);
                                    stt = 2;
                                }
                                break;
                            case '3':   //up
                                keybd_event(VK_UP, BK_UP, KEYDOWN, 0);
                                if (stt != 3)
                                {
                                    Thread.Sleep(200);
                                    stt = 3;
                                }
                                break;
                            case '4':   //left
                                keybd_event(VK_LEFT, BK_LEFT, KEYDOWN, 0);
                                if (stt != 4)
                                {
                                    Thread.Sleep(200);
                                    stt = 4;
                                }
                                break;
                            case '5':      //space or enter
                                if (rabSpace.Checked)
                                {
                                    keybd_event(VK_SPACE, BK_SPACE, KEYDOWN, 0);
                                    stt = 5;
                                }
                                else
                                {
                                    keybd_event(VK_ENTER, BK_ENTER, KEYDOWN, 0);
                                    stt = 6;
                                }
                                
                                
                                break;
                            case '6':   //no data
                                if (!((s.Contains(s1)) | (s.Contains(s2))|(s.Contains(s3))|(s.Contains(s4))|(s.Contains(s5))))
                                {
                                    count++;
                                    if ((count > 10) & ((stt!=0)|(hold)))
                                    {
                                        if (stt == 1) keybd_event(VK_DOWN, BK_DOWN, KEYUP, 0);
                                        if (stt == 2) keybd_event(VK_RIGHT, BK_RIGHT, KEYUP, 0);
                                        if (stt == 3) keybd_event(VK_UP, BK_UP, KEYUP, 0);
                                        if (stt == 4) keybd_event(VK_LEFT, BK_LEFT, KEYUP, 0);
                                        if (stt == 5) keybd_event(VK_SPACE, BK_SPACE, KEYUP, 0);
                                        if (stt == 6) keybd_event(VK_ENTER, BK_ENTER, KEYUP, 0);
                                        count = 0;
                                        stt = 0;
                                    }
                                }
                                break;   
                         }      //End of switch       

                  }   //End of while(on==1)

            }       //End of PbStart_Click

        private void txtSend_TextChanged(object sender, EventArgs e)
        {

        }

        private void cbbChooseGame_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void FrmUart_Load(object sender, EventArgs e)
        {

        }
    }   //End of Form
}       //End of NAMESPACE




                             //The old versiong using on-screen keyboard   
/* public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
public const int MOUSEEVENTF_RIGHTUP = 0x10;  
 * Cursor.Position = new Point(1025, 740);
    mouse_event(MOUSEEVENTF_LEFTDOWN , Cursor.Position.X, Cursor.Position.Y, 0, 0);
    mouse_up = false; 
    if ((stt != 1)&(!hold))
    {
        Thread.Sleep(200);
        mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
        COM.DiscardInBuffer();
        stt = 1;
 * 
 * 
 * case '6':   //no data
                                if (!((s.Contains(s1)) | (s.Contains(s2))|(s.Contains(s3))|(s.Contains(s4))|(s.Contains(s5))))
                                {
                                    count++;
                                    if ((count > 5) & ((stt!=0)|(hold)))
                                    {
                                        if (!mouse_up)
                                        {
                                            mouse_event(MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);
                                            mouse_up = true;
                                        }
                                        keybd_event(0x28, 0xD0, 0x02, 0);
                                        stt = 0;
                                        count = 0;
                                    }
                                }
    }   */